let stompClient = null
function setConnected(connected) {
    $("#connect").prop("disable",connected)
    $("#disconnect").prop("disable", !connected)

    if (connected) {
        $("#conversation").show()
        $("#chat").show()
    } else {
        $("#conversation").hide()
        $("#chat").hide()
    }

    $("#greetings").html("")
}

function connect(roomId) {
    if (!$("#name").val()) {
        return;
    }

    let socket = new SockJS('/ws')
    stompClient = Stomp.over(socket)
    stompClient.connect({},function (frame) {
        setConnected(true)
        stompClient.subscribe('/topic/' + roomId,function (msg) {
            showGreeting(JSON.parse(msg.body))
        })
    })
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect()
    }

    setConnected(false)
}

function sendName() {
    stompClient.send('/app/group',{},JSON.stringify(
        {
            'roomId': $("#room").val(),
            'userName': $("#name").val(),
            'content': $("#content").val()
        }
    ))
}

function showGreeting(message) {
    $("#greetings")
        .append("<div>" + message.userName + ":" + message.content + "</div>")
}

$(function () {
    $("#connect").click(function () {
        connect($("#room").val())
    })

    $("#disconnect").click(function () {
        disconnect()
    })

    $("#send").click(function () {
        sendName()
    })
})